package com.army.study.slice;

import com.army.study.MainAbility;
import com.army.study.ResourceTable;
import com.army.study.bean.MyPoint;
import com.army.study.component.*;
import com.army.study.utils.DistributedFileUtil;
import com.army.study.utils.GsonUtil;
import com.army.study.utils.LogUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.IDialog;
import ohos.agp.window.service.DisplayManager;
import ohos.agp.window.service.WindowManager;
import ohos.bundle.IBundleManager;
import ohos.data.distributed.common.*;
import ohos.data.distributed.user.SingleKvStore;
import ohos.media.image.PixelMap;
import ohos.utils.zson.ZSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_CONTENT;
import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT;
import static ohos.security.SystemPermission.*;

public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private static final String TAG = MainAbilitySlice.class.getName();
    private static final String PARAMETERS = "params";
    private static final String MESSAGE = "message";
    private static final int PERMISSION_CODE = 20220310;
    private static final float DENSITYFLOAT = 0.5f;
    // 画笔粗大小
    private static final int LINE_BIG_SIZE = 30;
    // 画笔正常大小
    private static final int LINE_SIZE = 15;
    // 画笔细大小
    private static final int LINE_SMALL_SIZE = 10;

    // 画笔种类
    private static final String DRAW_TYPE_SCREEN = "screen";    // 屏幕截图笔
    private static final String DRAW_TYPE_ERASER = "eraser";    // 橡皮擦
    private static final String DRAW_TYPE_PEN = "pen";          // 钢笔
    private static final String DRAW_TYPE_FLUORESCENCE = "fluorescence";    // 荧光笔
    private static final String DRAW_TYPE_PENCIL = "pencil";    // 铅笔

    // 画板各个点集合主键
    private static final String POINTS_KEY = "points";
    // 存储Id主键
    private static final String STORE_ID_KEY = "storeId";
    // 存储Id变量
    private static String storeId;
    // 是否来自本地设备主键
    private static final String IS_FORM_LOCAL_KEY = "isFormLocal";
    // 存储背景色变量
    private static final String BACKGROUND_COLOR = "currentBgColor";
    // 绘制类
    private DrawPoint drawl;
    // 画板组件
//    private DependentLayout canvas;
    private StackLayout canvas;
    private Image drawBg;
    // 延时毫秒数
    private static final int DELAY_TIME = 10;

    // 当前笔的颜色
//    private int currentDrawColor = 0xFF000000;
    private String currentDrawColor = "#000000";
    // 当前背景色
//    private int currentBgColor = 0xFFFFFFFF;
    private String currentBgColor = "#FFFFFF";
    // 当前笔粗细
    private int currentLineSize = LINE_SIZE;
    // 当前选择的颜色按钮
    private int currentSelectColorBtn = -1;
    // 当前画笔种类
    private String currentDrawType = DRAW_TYPE_PEN;

    private String bgImageMode = "white";
    private String openFileName = "";

    // 顶部组件
    private StackLayout bgModeView;
    private StackLayout btnBgMode;
    private Image bgLeftIcon;
    private Text bgText;
    private Image bgRightIcon;
    private Button btnShare;
    private Image imageUndo;
    private Image imageRedo;
    private Image imageDelete;
    private Text finish;
    private Button btnHistory;

    // 右边组件
//    private Image imagePenScreen;
    private Image imageEraser;
    private Image imagePen;
    private Image imagePenFluorescence;
//    private Image imagePencil;
    private StackLayout rightView;
    private StackLayout rightAndCenterIcon;
    private Image iconRightAndCenter;
    // 底部组件
    private Image imageRed;
    private Image imageGreen;
    private Image imageBlue;
    private Image imageBlack;
    private Image imageOther;
    private StackLayout bottomView;
    private StackLayout leftAndBottomIcon;
    private Image iconLeftAndBottom;
    private StackLayout bottomTopView;
    private Image imageWathet;
    private Image imageOrange;
    private Image imageYellow;
    private Image imageRoyalBlue;
    private Image imageCyan;
    private Image imagePurple;
    // 左边组件
    private Image imageBig;
    private Image imageLine;
    private Image imageSmall;
    private StackLayout leftView;
    private StackLayout lefAndCenterIcon;
    private Image iconLeftAndCenter;

    private KvManager kvManager;
    private SingleKvStore singleKvStore;
    // 分布式工具类
    private DistributedFileUtil fileUtil;

    @Override
    public void onStart(Intent intent) {
        // 全屏显示
        getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_NAVIGATION);
        WindowManager.getInstance().getTopWindow().get().setStatusBarVisibility(Component.INVISIBLE);
        WindowManager.getInstance().getTopWindow().get().addFlags(WindowManager.LayoutConfig.MARK_FULL_SCREEN);

        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        storeId = STORE_ID_KEY + System.currentTimeMillis();
        // 初始化分布式文件
        fileUtil = new DistributedFileUtil(this);
        // 获取组件根据Id
        findComponentById();
        // 动态权限请求
        requestPermission();
        // 初始化界面
        initView(intent);
        // 初始化数据库
        initDatabase();
        // 初始化绘制
        initDraw(intent);
        // 显示历史作品
        showHistory(intent);
    }

    private void showHistory(Intent intent) {
        if (null == intent) return;
        String params = intent.getStringParam(PARAMETERS);
        if (null == params) return;
        ZSONObject zsonObject = ZSONObject.stringToZSON(params);
        String message = zsonObject.getString(MESSAGE);
        LogUtil.info(TAG, message);
        if ("History".equalsIgnoreCase(message)) {
            showHistoryDialog();
        }else if("Lately".equalsIgnoreCase(message)) {
            showLatelyImage();
        }
    }


    /**
     * 初始化绘制
     * @param intent
     */
    private void initDraw(Intent intent) {
        // 初始化绘制画布
//        drawl = new DrawPoint(this, new Color(currentDrawColor));
        drawl = new DrawPoint(this, new Color(Color.getIntColor(currentDrawColor)) );
        // 画布宽度
        drawl.setWidth(MATCH_PARENT);
//        // 画布高度
//        drawl.setHeight(MATCH_PARENT);
        // 绘制画布添加到画板组件
        canvas.addComponent(drawl);

        // 获取数据库中的点数据，并在画布上画出来
        drawPoints();

        // 调用回调
        drawl.setOnDrawBack(points -> {
            if (points != null && points.size() > 1) {
                String pointsString = GsonUtil.objectToString(points);
                LogUtil.info(TAG, "pointsString::" + pointsString);
                if (singleKvStore != null) {
                    // 保存到分布式数据库
                    singleKvStore.putString(POINTS_KEY, pointsString);
                }
            }
        });

//        // 恢复撤消,重做,清空按钮状态
//        changeOpToolStatus();
    }

    /**
     * 获取数据库中的点数据，并在画布上画出来
     */
    private void drawPoints() {
        // 从数据库获取各个点的集合
        List<Entry> points = singleKvStore.getEntries(POINTS_KEY);
        // 循环获取点坐标
        for (Entry entry : points) {
            // 判断key是否包含points
            if (entry.getKey().equals(POINTS_KEY)) {
                // 字符串点集合转为List
                List<MyPoint> remotePoints = GsonUtil.jsonToList(singleKvStore.getString(POINTS_KEY), MyPoint.class);
                // 更新点并画到画板上
                getUITaskDispatcher().delayDispatch(() -> drawl.setDrawParams(remotePoints), DELAY_TIME);
            }
        }
    }

    /**
     * 初始化界面
     * @param intent
     */
    private void initView(Intent intent) {
        // 默认是本地端
        boolean isLocal = !intent.getBooleanParam(IS_FORM_LOCAL_KEY, false);
        // 如果是远程端
        if (!isLocal) {
            storeId = intent.getStringParam(STORE_ID_KEY);
            // 获取背景色
//            currentBgColor = intent.getIntParam(BACKGROUND_COLOR, 0xFFFFFFFF);
            currentBgColor = intent.getStringParam(BACKGROUND_COLOR);
//            ShapeElement element = new ShapeElement();
//            element.setRgbColor(RgbColor.fromArgbInt(currentBgColor));
//            canvas.setBackground(element);
//            if (currentBgColor == 0xFFFFFFFF) {
            if (currentBgColor.equalsIgnoreCase("#FFFFFF")) {
                bgImageMode = "white";
                drawBg.setPixelMap(ResourceTable.Media_bg_white);
            }else{
                bgImageMode = "eye";
                drawBg.setPixelMap(ResourceTable.Media_bg_eye);
            }
        }
        // 设置流转图标是否显示, 本地端显示服务流转图标, 远程端隐藏流转图标
        btnShare.setVisibility(isLocal ? Component.VISIBLE : Component.INVISIBLE);
    }

    private void requestPermission() {
        // 判断是否已经授权
        if (verifySelfPermission(DISTRIBUTED_DATASYNC) != IBundleManager.PERMISSION_GRANTED) {
            // 如果还没有授权, 弹窗出来让用户选择
            if (canRequestPermission(DISTRIBUTED_DATASYNC)) {
                requestPermissionsFromUser(new String[]{DISTRIBUTED_DATASYNC,WRITE_MEDIA,READ_MEDIA}, PERMISSION_CODE);
            }
        }
    }

    private void findComponentById() {
        // 界面顶部菜单框布局
        Button btnHome = (Button)findComponentById(ResourceTable.Id_btnHome);
        btnHome.setClickedListener(this);
        imageUndo = (Image)findComponentById(ResourceTable.Id_imageUndo);
        imageUndo.setClickedListener(this);
        imageRedo = (Image)findComponentById(ResourceTable.Id_imageRedo);
        imageRedo.setClickedListener(this);
        imageDelete = (Image)findComponentById(ResourceTable.Id_imageDelete);
        imageDelete.setClickedListener(this);
        btnShare = (Button)findComponentById(ResourceTable.Id_btnShare);
        btnShare.setClickedListener(this);
        bgLeftIcon = (Image)findComponentById(ResourceTable.Id_bgLeftIcon);
        bgText  = (Text)findComponentById(ResourceTable.Id_bgText);;
        bgRightIcon  = (Image)findComponentById(ResourceTable.Id_bgRightIcon);
        btnBgMode = (StackLayout)findComponentById(ResourceTable.Id_btnBgMode);
        btnBgMode.setClickedListener(this);
        finish = (Text)findComponentById(ResourceTable.Id_finish);
        finish.setClickedListener(this);
        btnHistory = (Button)findComponentById(ResourceTable.Id_btnHistory);
        btnHistory.setClickedListener(this);

        DirectionalLayout btnWhiteBoard = (DirectionalLayout)findComponentById(ResourceTable.Id_btnWhiteBoard);
        btnWhiteBoard.setClickedListener(this);
        DirectionalLayout btnEyeBoard = (DirectionalLayout)findComponentById(ResourceTable.Id_btnEyeBoard);
        btnEyeBoard.setClickedListener(this);

        bgModeView = (StackLayout)findComponentById(ResourceTable.Id_bgModeView);
        ShadowDrawable.setShadowDrawable(bgModeView, Color.getIntColor("#FFFFFF"), dpToPx(20),Color.getIntColor("#1A000000"), dpToPx(10), 0, 2);
        bgModeView.setVisibility(Component.INVISIBLE);
        StackLayout topView = (StackLayout)findComponentById(ResourceTable.Id_topView);
        ShadowDrawable.setShadowDrawable(topView, Color.getIntColor("#FFFFFF"), 0,Color.getIntColor("#1A000000"), dpToPx(10), 0, 2);

        // 界面右边菜单框布局
//        imagePenScreen = (Image) findComponentById(ResourceTable.Id_imagePenScreen);
//        imagePenScreen.setClickedListener(this);
        imageEraser = (Image) findComponentById(ResourceTable.Id_imageEraser);
        imageEraser.setClickedListener(this);
        imagePen = (Image) findComponentById(ResourceTable.Id_imagePen);
        imagePen.setPixelMap(ResourceTable.Media_pen_2x);
        imagePen.setClickedListener(this);
        imagePenFluorescence = (Image) findComponentById(ResourceTable.Id_imagePenFluorescence);
        imagePenFluorescence.setClickedListener(this);
//        imagePencil = (Image) findComponentById(ResourceTable.Id_imagePencil);
//        imagePencil.setClickedListener(this);
        rightAndCenterIcon = (StackLayout)findComponentById(ResourceTable.Id_rightAndCenterIcon);
        rightAndCenterIcon.setClickedListener(this);
        iconRightAndCenter = (Image)findComponentById(ResourceTable.Id_iconRightAndCenter);
        iconRightAndCenter.setPixelMap(ResourceTable.Media_icon_right_2x_R);
        rightView = (StackLayout)findComponentById(ResourceTable.Id_rightView);
        rightView.setVisibility(Component.VISIBLE);
        //设置背景为颜色为#2979FF，圆角为8dp, 阴影颜色为#992979FF，宽度为6dp的背景
        ShadowDrawable.setShadowDrawable(rightView, Color.getIntColor("#FFFFFF"), dpToPx(30),Color.getIntColor("#1A000000"), dpToPx(10), 0, -2);

        // 界面底部菜单框布局
        imageRed = (Image)findComponentById(ResourceTable.Id_imageRed);
        imageRed.setClickedListener(this);
        imageGreen = (Image)findComponentById(ResourceTable.Id_imageGreen);
        imageGreen.setClickedListener(this);
        imageBlue = (Image)findComponentById(ResourceTable.Id_imageBlue);
        imageBlue.setClickedListener(this);
        imageBlack = (Image)findComponentById(ResourceTable.Id_imageBlack);
        imageBlack.setClickedListener(this);
        imageBlack.setPixelMap(ResourceTable.Media_black_2x);
//        currentDrawColor = 0xFF000000;
        currentDrawColor = "#000000";
        imageOther = (Image)findComponentById(ResourceTable.Id_imageOther);
        imageOther.setClickedListener(this);
        leftAndBottomIcon = (StackLayout)findComponentById(ResourceTable.Id_leftAndBottomIcon);
        leftAndBottomIcon.setClickedListener(this);
        iconLeftAndBottom = (Image)findComponentById(ResourceTable.Id_iconLeftAndBottom);
        iconLeftAndBottom.setPixelMap(ResourceTable.Media_icon_bottom_2x);
        bottomView = (StackLayout)findComponentById(ResourceTable.Id_bottomView);
        bottomView.setVisibility(Component.VISIBLE);
        ShadowDrawable.setShadowDrawable(bottomView, Color.getIntColor("#FFFFFF"), dpToPx(30),Color.getIntColor("#1A000000"), dpToPx(10), 0, -2);
        // 界面底部上菜单框布局
        imageWathet = (Image)findComponentById(ResourceTable.Id_imageWathet);
        imageWathet.setClickedListener(this);
        imageOrange = (Image)findComponentById(ResourceTable.Id_imageOrange);
        imageOrange.setClickedListener(this);
        imageYellow = (Image)findComponentById(ResourceTable.Id_imageYellow);
        imageYellow.setClickedListener(this);
        imageRoyalBlue = (Image)findComponentById(ResourceTable.Id_imageRoyalBlue);
        imageRoyalBlue.setClickedListener(this);
        imageCyan = (Image)findComponentById(ResourceTable.Id_imageCyan);
        imageCyan.setClickedListener(this);
        imagePurple = (Image)findComponentById(ResourceTable.Id_imagePurple);
        imagePurple.setClickedListener(this);
        bottomTopView = (StackLayout)findComponentById(ResourceTable.Id_bottomTopView);
        bottomTopView.setVisibility(Component.INVISIBLE);
        ShadowDrawable.setShadowDrawable(bottomTopView, Color.getIntColor("#FFFFFF"), dpToPx(30),Color.getIntColor("#1A000000"), dpToPx(10), 0, -2);

        // 界面左边菜单框布局
        imageBig = (Image)findComponentById(ResourceTable.Id_imageBig);
        imageBig.setClickedListener(this);
        imageLine = (Image)findComponentById(ResourceTable.Id_imageLine);
        imageLine.setClickedListener(this);
        imageLine.setPixelMap(ResourceTable.Media_line_2x);
        imageSmall = (Image)findComponentById(ResourceTable.Id_imageSmall);
        imageSmall.setClickedListener(this);
        lefAndCenterIcon = (StackLayout)findComponentById(ResourceTable.Id_lefAndCenterIcon);
        lefAndCenterIcon.setClickedListener(this);
        iconLeftAndCenter = (Image)findComponentById(ResourceTable.Id_iconLeftAndCenter);
        iconLeftAndCenter.setPixelMap(ResourceTable.Media_icon_left_2x_L);
        leftView = (StackLayout)findComponentById(ResourceTable.Id_leftView);
        leftView.setVisibility(Component.VISIBLE);
        ShadowDrawable.setShadowDrawable(leftView, Color.getIntColor("#FFFFFF"), dpToPx(30),Color.getIntColor("#1A000000"), dpToPx(10), 0, -2);

        // 画板
//        if (findComponentById(ResourceTable.Id_canvas) instanceof DependentLayout) {
//            canvas = (DependentLayout) findComponentById(ResourceTable.Id_canvas);
//            ShapeElement element = new ShapeElement();
//            element.setRgbColor(RgbColor.fromArgbInt(currentBgColor));
//            canvas.setBackground(element);
//        }
        canvas = (StackLayout) findComponentById(ResourceTable.Id_canvas);
        drawBg = (Image) findComponentById(ResourceTable.Id_drawBg);

    }

    private int dpToPx(int dp) {
        float density = DisplayManager.getInstance().getDefaultDisplay(this).get().getAttributes().densityPixels;
        return (int) (dp * density + DENSITYFLOAT);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
        // 显示历史作品
        showHistory(intent);
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            // 顶部按钮事件
            case ResourceTable.Id_btnHome:
                terminateAbility();
                break;
            case ResourceTable.Id_imageUndo:
//                changeOpToolStatus();
//                imageUndo.setPixelMap(ResourceTable.Media_icon_undo_2x);
                undoLastDraw();
                break;
            case ResourceTable.Id_imageRedo:
//                changeOpToolStatus();
//                imageRedo.setPixelMap(ResourceTable.Media_icon_redo_2x);
                redoLastDraw();
                break;
            case ResourceTable.Id_imageDelete:
//                changeOpToolStatus();
//                imageDelete.setPixelMap(ResourceTable.Media_icon_delete_2x);
                clearDraw();
                break;
            case ResourceTable.Id_btnShare:
                showDeviceSelectDialog();
                break;
            case ResourceTable.Id_btnBgMode:
                showAndHideBgModeView();
                break;
            case ResourceTable.Id_btnWhiteBoard:
//                currentBgColor = 0xFFFFFFFF;
                currentBgColor = "#FFFFFF";
                bgImageMode = "white";
                showAndHideBgModeView();
                break;
            case ResourceTable.Id_btnEyeBoard:
                currentBgColor = "#C7EECC";
                bgImageMode = "eye";
                showAndHideBgModeView();
                break;
            case ResourceTable.Id_finish:
                saveImage();
                break;
            case ResourceTable.Id_btnHistory:
                showHistoryDialog();
                break;
            // 右边按钮事件
//            case ResourceTable.Id_imagePenScreen:
//                currentDrawType = DRAW_TYPE_SCREEN;
//                changeRightPenStatus(ResourceTable.Id_imagePenScreen);
//                imagePenScreen.setPixelMap(ResourceTable.Media_pen33_2x);
//                break;
            case ResourceTable.Id_imageEraser:
                currentDrawType = DRAW_TYPE_ERASER;
                changeRightPenStatus(ResourceTable.Id_imageEraser);
                imageEraser.setPixelMap(ResourceTable.Media_eraser_2x);
                break;
            case ResourceTable.Id_imagePen:
                currentDrawType = DRAW_TYPE_PEN;
                changeRightPenStatus(ResourceTable.Id_imagePen);
                imagePen.setPixelMap(ResourceTable.Media_pen_2x);
                break;
            case ResourceTable.Id_imagePenFluorescence:
                currentDrawType = DRAW_TYPE_FLUORESCENCE;
                changeRightPenStatus(ResourceTable.Id_imagePenFluorescence);
                imagePenFluorescence.setPixelMap(ResourceTable.Media_pen22_2x);
                break;
//            case ResourceTable.Id_imagePencil:
//                currentDrawType = DRAW_TYPE_PENCIL;
//                changeRightPenStatus(ResourceTable.Id_imagePencil);
//                imagePencil.setPixelMap(ResourceTable.Media_pen11_2x);
//                break;
            case ResourceTable.Id_rightAndCenterIcon:
                showAndHideRightView();
                break;
            // 底部按钮事件
            case ResourceTable.Id_imageRed:
                currentSelectColorBtn = ResourceTable.Id_imageRed;
//                currentDrawColor = 0xFFE02020;
                currentDrawColor = "#E02020";
                changeBottomColorStatus(ResourceTable.Id_imageRed);
                imageRed.setPixelMap(ResourceTable.Media_red_2x);
                bottomTopView.setVisibility(Component.INVISIBLE);
                break;
            case ResourceTable.Id_imageGreen:
                currentSelectColorBtn = ResourceTable.Id_imageGreen;
//                currentDrawColor = 0xFF6DD400;
                currentDrawColor = "#6DD400";
                changeBottomColorStatus(ResourceTable.Id_imageGreen);
                imageGreen.setPixelMap(ResourceTable.Media_green_2x);
                bottomTopView.setVisibility(Component.INVISIBLE);
                break;
            case ResourceTable.Id_imageBlue:
                currentSelectColorBtn = ResourceTable.Id_imageBlue;
//                currentDrawColor = 0xFF0091FF;
                currentDrawColor = "#0091FF";
                changeBottomColorStatus(ResourceTable.Id_imageBlue);
                imageBlue.setPixelMap(ResourceTable.Media_blue_2x);
                bottomTopView.setVisibility(Component.INVISIBLE);
                break;
            case ResourceTable.Id_imageBlack:
                currentSelectColorBtn = ResourceTable.Id_imageBlack;
//                currentDrawColor = 0xFF000000;
                currentDrawColor = "#000000";
                changeBottomColorStatus(ResourceTable.Id_imageBlack);
                imageBlack.setPixelMap(ResourceTable.Media_black_2x);
                bottomTopView.setVisibility(Component.INVISIBLE);
                break;
            case ResourceTable.Id_imageOther:
                currentSelectColorBtn = ResourceTable.Id_imageOther;
//                currentDrawColor = 0xFF000000;
                currentDrawColor = "#000000";
                changeBottomColorStatus(ResourceTable.Id_imageOther);
                imageOther.setPixelMap(ResourceTable.Media_other_2x);
                bottomTopView.setVisibility(Component.VISIBLE);
                break;
            case ResourceTable.Id_imageWathet:
                currentSelectColorBtn = ResourceTable.Id_imageWathet;
//                currentDrawColor = 0xFF32C5FF;
                currentDrawColor = "#32C5FF";
                changeBottomAndTopColorStatus();
                imageWathet.setPixelMap(ResourceTable.Media_wathet_2x);
                break;
            case ResourceTable.Id_imageOrange:
                currentSelectColorBtn = ResourceTable.Id_imageOrange;
//                currentDrawColor = 0xFFFA6400;
                currentDrawColor = "#FA6400";
                changeBottomAndTopColorStatus();
                imageOrange.setPixelMap(ResourceTable.Media_orange_2x);
                break;
            case ResourceTable.Id_imageYellow:
                currentSelectColorBtn = ResourceTable.Id_imageYellow;
//                currentDrawColor = 0xFFF7B500;
                currentDrawColor = "#F7B500";
                changeBottomAndTopColorStatus();
                imageYellow.setPixelMap(ResourceTable.Media_yellow_2x);
                break;
            case ResourceTable.Id_imageRoyalBlue:
                currentSelectColorBtn = ResourceTable.Id_imageRoyalBlue;
//                currentDrawColor = 0xFF6236FF;
                currentDrawColor = "#6236FF";
                changeBottomAndTopColorStatus();
                imageRoyalBlue.setPixelMap(ResourceTable.Media_royalBlue_2x);
                break;
            case ResourceTable.Id_imageCyan:
                currentSelectColorBtn = ResourceTable.Id_imageCyan;
//                currentDrawColor = 0xFF44D7B6;
                currentDrawColor = "#44D7B6";
                changeBottomAndTopColorStatus();
                imageCyan.setPixelMap(ResourceTable.Media_cyan_2x);
                break;
            case ResourceTable.Id_imagePurple:
                currentSelectColorBtn = ResourceTable.Id_imagePurple;
//                currentDrawColor = 0xFFB620E0;
                currentDrawColor = "#B620E0";
                changeBottomAndTopColorStatus();
                imagePurple.setPixelMap(ResourceTable.Media_purple_2x);
                break;
            case ResourceTable.Id_leftAndBottomIcon:
                showAndHideBottomView();
                break;
            // 左边按钮事件
            case ResourceTable.Id_imageBig:
                currentLineSize = LINE_BIG_SIZE;
                changeLeftLineSizeStatus();
                imageBig.setPixelMap(ResourceTable.Media_line_big_2x);
                break;
            case ResourceTable.Id_imageLine:
                currentLineSize = LINE_SIZE;
                changeLeftLineSizeStatus();
                imageLine.setPixelMap(ResourceTable.Media_line_2x);
                break;
            case ResourceTable.Id_imageSmall:
                currentLineSize = LINE_SMALL_SIZE;
                changeLeftLineSizeStatus();
                imageSmall.setPixelMap(ResourceTable.Media_line_small_2x);
                break;
            case ResourceTable.Id_lefAndCenterIcon:
                showAndHideLeftView();
                break;
            default:
                break;
        }
    }

    /**
     * 完成保存图片
     */
    private String fileName = "";
    private void saveImage() {
//        fileName = new Date().getTime()+"_";
        if (bgImageMode.equalsIgnoreCase("history")
            || bgImageMode.equalsIgnoreCase("lately")) {
            fileName = openFileName.substring(0, openFileName.indexOf("."));
            fileUtil.writeLetter(fileName, drawl.getPoints(), bgImageMode);
        }else{
            SaveConfirmDialog saveConfirmDialog = new SaveConfirmDialog(MainAbilitySlice.this);
            saveConfirmDialog.setOnCallBack(name -> {
                fileName = new Date().getTime()+"_"+name;
                fileUtil.writeLetter(fileName, drawl.getPoints(), bgImageMode);
            });
            saveConfirmDialog.show();
        }
    }

    /**
     * 弹出多屏协同对话框
     */
    private void showDeviceSelectDialog() {
        DeviceSelectDialog dialog = new DeviceSelectDialog(MainAbilitySlice.this);
        dialog.setListener(deviceIds -> {
            if (deviceIds != null && !deviceIds.isEmpty()) {
                // 启动远程页面
                startRemoteFas(deviceIds);
                // 同步远程数据库
                singleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY);
            }
            dialog.hide();
        });
        dialog.show();
    }

    /**
     * 弹出历史作品对话框
     */
    private void showHistoryDialog() {
        HistoryDialog dialog = new HistoryDialog(MainAbilitySlice.this, fileUtil);
        dialog.setConfirmListener(selectFileName -> {
            if (selectFileName != null && !selectFileName.isEmpty()) {
                // 打开图片
                openFileName = selectFileName;
                bgImageMode = "history";
                openHistory(selectFileName);
                // 同步远程数据库
//                singleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY);
            }
            dialog.hide();
        });

        dialog.setDeleteListener(selectFileName -> {
            if (selectFileName != null && !selectFileName.isEmpty()) {
                CommonDialog confirmDialog = new CommonDialog(getContext());
                confirmDialog.setTitleText("温馨提示");
                confirmDialog.setContentText("确定要删除手稿吗?");
                confirmDialog.setSize(600, 400);
                confirmDialog.setButton(IDialog.BUTTON1, "取消", (iDialog, i) -> iDialog.destroy());
                confirmDialog.setButton(IDialog.BUTTON2, "确定", (iDialog, i) -> {
                    // 删除当前图片
                    boolean result = fileUtil.deleteImage(selectFileName);
                    if (result) {
                        dialog.setAdapter();
                    }
                    iDialog.destroy();
                });
                confirmDialog.show();

            }
        });

        dialog.show();
    }

    private void openHistory(String selectFileName) {
        PixelMap pixelMap = fileUtil.readImage(selectFileName);
        drawBg.setPixelMap(pixelMap);
    }

    /**
     * 显示最近手稿
     */
    private void showLatelyImage() {
        bgImageMode = "lately";
        List<String> fileList = fileUtil.getFileList();
        if (fileList.size() < 1) return;

        String selectFileName = fileList.get(0);
        openFileName = selectFileName;
        PixelMap pixelMap = fileUtil.readImage(selectFileName);
        drawBg.setPixelMap(pixelMap);
    }

    /**
     * 启动远程页面
     * @param deviceIds
     */
    private void startRemoteFas(List<String> deviceIds) {
        Intent[] intents = new Intent[deviceIds.size()];
        for (int i = 0; i < deviceIds.size(); i++) {
            Intent intent = new Intent();
            intent.setParam(IS_FORM_LOCAL_KEY, true);
            intent.setParam(BACKGROUND_COLOR, currentBgColor);
            intent.setParam(STORE_ID_KEY, storeId);
            Operation operation = new Intent.OperationBuilder()
                    .withDeviceId(deviceIds.get(i))
                    .withBundleName(getBundleName())
                    .withAbilityName(MainAbility.class.getName())
                    .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                    .build();
            intent.setOperation(operation);
            intents[i] = intent;
        }
        startAbilities(intents);
    }

    /**
     * 初始化数据库
     */
    private void initDatabase() {
        // 初始化管理配置
        KvManagerConfig config = new KvManagerConfig(this);
        // 创建分布式数据库管理对象
        kvManager = KvManagerFactory.getInstance().createKvManager(config);
        // 创建分布式数据库
        Options options = new Options();
        // 设置如果没有可用的KvStore数据库，是否创建KvStore数据库
        options.setCreateIfMissing(true)
                .setEncrypt(false)  // 设置是否加密KvStore数据库
                .setKvStoreType(KvStoreType.SINGLE_VERSION); // 设置KvStore数据库的类型(单版本数据库，由SingleKvStore指定)
        // 获取分布式数据库
        singleKvStore = kvManager.getKvStore(options, storeId);
        // 订阅分布式数据变化
        KvStoreObserver kvStoreObserverClient = new KvStoreObserverClient();
        singleKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL, kvStoreObserverClient);
    }

    /**
     * 接收数据库消息
     */
    private class KvStoreObserverClient implements KvStoreObserver {
        @Override
        public void onChange(ChangeNotification notification) {
            LogUtil.info(TAG, "data changed......");
            // 获取数据库中的点数据，并在画布上画出来
            drawPoints();
        }
    }

    /**
     * 显示或隐藏背景色
     */
    private void showAndHideBgModeView() {
//        if (currentBgColor == 0xFFFFFFFF) {
        if (currentBgColor.equalsIgnoreCase("#FFFFFF")) {
            bgLeftIcon.setPixelMap(ResourceTable.Media_icon_white_board);
            bgText.setText("白板");
            drawBg.setPixelMap(ResourceTable.Media_bg_white);
        }else{
            bgLeftIcon.setPixelMap(ResourceTable.Media_icon_eye_board);
            bgText.setText("护目");
            drawBg.setPixelMap(ResourceTable.Media_bg_eye);
        }

        if (bgModeView.getVisibility() == 0) {
            bgModeView.setVisibility(Component.INVISIBLE);
            bgRightIcon.setPixelMap(ResourceTable.Media_btn_bottom);
        }else if(bgModeView.getVisibility() == 1) {
            bgModeView.setVisibility(Component.VISIBLE);
            bgRightIcon.setPixelMap(ResourceTable.Media_btn_top);
        }

        // 当前是橡皮擦,更改画笔颜色为背景色
        if (currentDrawType.equalsIgnoreCase(DRAW_TYPE_ERASER)) {
            currentDrawColor = currentBgColor;
//            drawl.setPaintColor(new Color(currentDrawColor));
            drawl.setPaintColor(new Color(Color.getIntColor(currentDrawColor)) );
        }

//        // 设置背景色
//        ShapeElement element = new ShapeElement();
//        element.setRgbColor(RgbColor.fromArgbInt(currentBgColor));
//        canvas.setBackground(element);

    }

    /**
     * 撤消, 重做, 清空 状态
     */
//    private void changeOpToolStatus() {
//        imageUndo.setPixelMap(ResourceTable.Media_icon_undo_1x);
//        imageRedo.setPixelMap(ResourceTable.Media_icon_redo_1x);
//        imageDelete.setPixelMap(ResourceTable.Media_icon_delete_1x);
//    }

    /**
     * 显示或隐藏右边组件
     */
    private void showAndHideRightView() {
        if (rightView.getVisibility() == 0) {
            iconRightAndCenter.setPixelMap(ResourceTable.Media_icon_left_2x_R);
            rightView.setVisibility(Component.INVISIBLE);
        }else if (rightView.getVisibility() == 1) {
            iconRightAndCenter.setPixelMap(ResourceTable.Media_icon_right_2x_R);
            rightView.setVisibility(Component.VISIBLE);
        }
    }

    /**
     * 显示或隐藏底部组件
     */
    private void showAndHideBottomView() {
        if (bottomView.getVisibility() == 0) {
            iconLeftAndBottom.setPixelMap(ResourceTable.Media_icon_top_2x);
            bottomView.setVisibility(Component.INVISIBLE);
            bottomTopView.setVisibility(Component.INVISIBLE);
        }else if (bottomView.getVisibility() == 1) {
            iconLeftAndBottom.setPixelMap(ResourceTable.Media_icon_bottom_2x);
            bottomView.setVisibility(Component.VISIBLE);
            // 如果当前选择的是其它颜色按钮,才显示出上面的颜色块
            if (ResourceTable.Id_imageOther == currentSelectColorBtn) {
                bottomTopView.setVisibility(Component.VISIBLE);
            }
        }
    }

    /**
     * 显示或隐藏左边组件
     */
    private void showAndHideLeftView() {
        if (leftView.getVisibility() == 0) {
            iconLeftAndCenter.setPixelMap(ResourceTable.Media_icon_right_2x_L);
            leftView.setVisibility(Component.INVISIBLE);
        }else if (leftView.getVisibility() == 1) {
            iconLeftAndCenter.setPixelMap(ResourceTable.Media_icon_left_2x_L);
            leftView.setVisibility(Component.VISIBLE);
        }
    }

    /**
     * 修改右边组件画笔,橡皮为默认状态
     */
    private void changeRightPenStatus(int id) {
//        imagePenScreen.setPixelMap(ResourceTable.Media_pen33_1x);
        imageEraser.setPixelMap(ResourceTable.Media_eraser_1x);
        imagePen.setPixelMap(ResourceTable.Media_pen_1x);
        imagePenFluorescence.setPixelMap(ResourceTable.Media_pen22_1x);
//        imagePencil.setPixelMap(ResourceTable.Media_pen11_1x);

        drawl.setPaintAlpha(1.0f);
//        drawl.setPaintColor(new Color(currentDrawColor));
        drawl.setPaintColor(new Color(Color.getIntColor(currentDrawColor)) );
        if (id == ResourceTable.Id_imagePenFluorescence) {
            drawl.setPaintAlpha(0.5f);
        }else if (id == ResourceTable.Id_imageEraser) {
//            currentDrawColor = currentBgColor;
            drawl.setPaintColor(new Color(Color.getIntColor(currentBgColor)) );
        }
    }

    /**
     * 修改底部组件默认状态
     */
    private void changeBottomColorStatus(int id) {
        imageRed.setPixelMap(ResourceTable.Media_red_1x);
        imageGreen.setPixelMap(ResourceTable.Media_green_1x);
        imageBlue.setPixelMap(ResourceTable.Media_blue_1x);
        imageBlack.setPixelMap(ResourceTable.Media_black_1x);
        imageOther.setPixelMap(ResourceTable.Media_other_1x);
        // 如果点击其它颜色不重置, 上面颜色模块
        if (id != ResourceTable.Id_imageOther) {
            this.changeBottomAndTopColorStatus();
        }
        // 如果当前画笔类型是橡皮擦, 画笔颜色改为背景色
        if (currentDrawType.equalsIgnoreCase(DRAW_TYPE_ERASER)) {
            currentDrawColor = currentBgColor;
        }
        // 修改画笔颜色
//        drawl.setPaintColor(new Color(currentDrawColor));
        drawl.setPaintColor(new Color(Color.getIntColor(currentDrawColor)) );
    }

    /**
     * 修改底部上组件默认状态
     */
    private void changeBottomAndTopColorStatus() {
        imageWathet.setPixelMap(ResourceTable.Media_wathet_1x);
        imageOrange.setPixelMap(ResourceTable.Media_orange_1x);
        imageYellow.setPixelMap(ResourceTable.Media_yellow_1x);
        imageRoyalBlue.setPixelMap(ResourceTable.Media_royalBlue_1x);
        imageCyan.setPixelMap(ResourceTable.Media_cyan_1x);
        imagePurple.setPixelMap(ResourceTable.Media_purple_1x);
        // 如果当前画笔类型是橡皮擦, 画笔颜色改为背景色
        if (currentDrawType.equalsIgnoreCase(DRAW_TYPE_ERASER)) {
            currentDrawColor = currentBgColor;
        }
        // 修改画笔颜色
//        drawl.setPaintColor(new Color(currentDrawColor));
        drawl.setPaintColor(new Color(Color.getIntColor(currentDrawColor)) );
    }

    /**
     * 修改左边线条默认状态
     */
    private void changeLeftLineSizeStatus() {
        imageBig.setPixelMap(ResourceTable.Media_line_big_1x);
        imageLine.setPixelMap(ResourceTable.Media_line_1x);
        imageSmall.setPixelMap(ResourceTable.Media_line_small_1x);
        // 修改画笔粗细
        drawl.setStrokeWidth(currentLineSize);
    }

    /**
     * 撤消最近一次绘画
     */
    private void undoLastDraw() {
        // 获取到所有绘制点
        List<MyPoint> points = drawl.getPoints();
        if (points == null || points.size() <= 1) {
            return;
        }

        // 添加撤消一画到重做集合
        List<MyPoint> redoPoints = drawl.getRedoPoints();
        redoPoints.add(points.get(points.size()-1));
        // 删除最近一画
        points.remove(points.size() - 1);
        for (int i = points.size() -1; i >= 0; i--) {
            if (points.get(i).isLastPoint()) {
                break;
            }
            redoPoints.add(points.get(i));
            points.remove(i);
        }
        drawl.setDrawRedoPoints(redoPoints);
        // 重新设置绘画点到画板上
        drawl.setDrawParams(points);

        // 重新保存到分布式数据库
        String pointsString = GsonUtil.objectToString(points);
        LogUtil.info(TAG, "pointsString::" + pointsString);
        if (singleKvStore != null) {
            // 保存到分布式数据库
            singleKvStore.putString(POINTS_KEY, pointsString);
        }
    }

    /**
     * 重做最近撤消的绘画
     */
    private void redoLastDraw() {
        // 获取可以重做的绘制点
        List<MyPoint> redoPoints = drawl.getRedoPoints();
        if (redoPoints == null || redoPoints.size() <= 1) {
            return;
        }

        // 获取到所有绘制点
        List<MyPoint> points = drawl.getPoints();
        points.add(redoPoints.get(redoPoints.size() - 1));

        // 删除最近撤消一画
        redoPoints.remove(redoPoints.size() - 1);
        for (int i = redoPoints.size() -1; i >= 0; i--) {
            if (redoPoints.get(i).isLastPoint()) {
                break;
            }
            points.add(redoPoints.get(i));
            redoPoints.remove(i);
        }
        drawl.setDrawRedoPoints(redoPoints);
        // 重新设置绘画点到画板上
        drawl.setDrawParams(points);

        // 重新保存到分布式数据库
        String pointsString = GsonUtil.objectToString(points);
        LogUtil.info(TAG, "pointsString::" + pointsString);
        if (singleKvStore != null) {
            // 保存到分布式数据库
            singleKvStore.putString(POINTS_KEY, pointsString);
        }
    }

    /**
     * 清除画布所有绘画
     */
    private void clearDraw() {
        List<MyPoint> points = new ArrayList<>(0);
        // 重新设置绘画点到画板上
        drawl.setDrawParams(points);
        drawl.setDrawRedoPoints(points);

        // 重新保存到分布式数据库
        String pointsString = GsonUtil.objectToString(points);
        LogUtil.info(TAG, "pointsString::" + pointsString);
        if (singleKvStore != null) {
            // 保存到分布式数据库
            singleKvStore.putString(POINTS_KEY, pointsString);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        kvManager.closeKvStore(singleKvStore);
    }
}
